<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2017/7/13
 * Time: 14:09
 */
namespace app\admin\controller;
use think\Db;
use think\Request;

class AssessmentCycleController extends BaseController{
    //评估周期列表
    public function lst(){
      $cycles = Db::table('assessment_cycle')->where('is_del!=1')->select();
        $this->assign('cycle',$cycles);
        return $this->fetch();

    }
    //添加评估周期
    public function add(){
        if(Request::instance()->isPost()){
            $data = [
                'name'=>Request::instance()->param('name'),
            ];
            $validate = validate('AssessmentCycle');
            if($validate->check($data)){
                //添加数据
                $insertData = [
                    'name'=>$data['name'],
                    'created_time'=>time(),
                    'updated_time'=>time(),
                ];
                $re = Db::table('assessment_cycle')->insert($insertData);
                if($re){
                    $this->success('添加成功',url('assessmentCycle/lst'));
                }else{
                    $this->error('添加失败',url('assessmentCycle/add'));
                }
            }else{
              $errors = $validate->getError();
              $this->error('添加失败,'.$errors,url('assessmentCycle/add'));
            }
        }
        return $this->fetch();
    }
    //编辑评估周期
    public function edit(){
        $id = Request::instance()->param('id');
        $cycle = Db::table('assessment_cycle')->where('id',$id)->find();
        if(Request::instance()->isPost()){
            $data = [
                'name'=>Request::instance()->param('name'),
            ];
            $validate = validate('AssessmentCycle');
            if($validate->scene('edit')->check($data)){
                //已存在的名称修改失败
                $cycle_name = Db::table('assessment_cycle')->where('name',$data['name'])->find();
                if($cycle_name && $cycle['name'] !=$data['name']){
                    $this->error('名称已存在',url('assessmentCycle/edit',['id'=>$id]));
                }else{
                    $insertData = [
                        'name'=>$data['name'],
                        'updated_time'=>time(),
                    ];
                    $re = Db::table('assessment_cycle')->where('id',$id)->update($insertData);
                    if($re){
                        $this->success('修改成功',url('assessmentCycle/lst'));
                    }else{
                        $this->error('修改失败',url('assessmentCycle/edit',['id'=>$id]));
                    }
                }
            }else{
                $errors = $validate->getError();
                $this->error('添加失败,'.$errors,url('assessmentCycle/edit',['id'=>$id]));
            }
        }
        $this->assign('cycle',$cycle);
        return $this->fetch();
    }


}